<template>
  <div class="recipes-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item>
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索食谱"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-select v-model="filterForm.category" placeholder="食谱分类" clearable>
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-select v-model="filterForm.difficulty" placeholder="难度等级" clearable>
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-select v-model="filterForm.time" placeholder="烹饪时间" clearable>
            <el-option label="15分钟以内" value="15" />
            <el-option label="30分钟以内" value="30" />
            <el-option label="60分钟以内" value="60" />
            <el-option label="60分钟以上" value="60+" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排序方式" prop="sortBy">
          <el-radio-group v-model="filterForm.sortBy">
            <el-radio-button value="popularity">热门程度</el-radio-button>
            <el-radio-button value="rating">评分</el-radio-button>
            <el-radio-button value="time">制作时间</el-radio-button>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 食谱列表 -->
    <el-row :gutter="20" class="recipe-list">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="recipe in recipes" :key="recipe.id">
        <el-card class="recipe-card" :body-style="{ padding: '0px' }">
          <div class="recipe-image">
            <el-image :src="recipe.image" fit="cover">
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="recipe-tags">
              <el-tag size="small" :type="getDifficultyType(recipe.difficulty)">
                {{ recipe.difficulty }}
              </el-tag>
              <el-tag size="small" type="info">{{ recipe.cookingTime }}分钟</el-tag>
            </div>
          </div>
          
          <div class="recipe-content">
            <h3 class="recipe-title" @click="showRecipeDetail(recipe)">
              {{ recipe.name }}
            </h3>
            <p class="recipe-desc">{{ recipe.description }}</p>
            <div class="recipe-info">
              <div class="nutrition-info">
                <span>{{ recipe.calories }}kcal</span>
                <el-divider direction="vertical" />
                <span>蛋白质{{ recipe.protein }}g</span>
              </div>
              <div class="action-buttons">
                <el-button
                  :type="recipe.isFavorite ? 'danger' : 'default'"
                  :icon="recipe.isFavorite ? StarFilled : Star"
                  circle
                  @click="toggleFavorite(recipe)"
                />
                <el-button
                  type="primary"
                  :icon="Plus"
                  circle
                  @click="addToMealPlan(recipe)"
                />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 食谱详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentRecipe?.name"
      width="60%"
      class="recipe-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <h3>{{ currentRecipe?.name }}</h3>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="烹饪时间">{{ currentRecipe?.cookingTime }}分钟</el-descriptions-item>
        <el-descriptions-item label="难度">{{ currentRecipe?.difficulty }}</el-descriptions-item>
        <el-descriptions-item label="热量">{{ currentRecipe?.calories }}kcal</el-descriptions-item>
        <el-descriptions-item label="蛋白质">{{ currentRecipe?.protein }}g</el-descriptions-item>
        <el-descriptions-item label="碳水化合物">{{ currentRecipe?.carbs }}g</el-descriptions-item>
        <el-descriptions-item label="脂肪">{{ currentRecipe?.fat }}g</el-descriptions-item>
      </el-descriptions>

      <div class="recipe-detail">
        <h4>食材</h4>
        <el-table :data="currentRecipe?.ingredients" border stripe>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="amount" label="用量" />
          <el-table-column prop="unit" label="单位" />
        </el-table>

        <h4>步骤</h4>
        <el-timeline>
          <el-timeline-item
            v-for="(step, index) in currentRecipe?.steps"
            :key="index"
            :timestamp="`步骤 ${index + 1}`"
          >
            {{ step }}
          </el-timeline-item>
        </el-timeline>

        <h4>小贴士</h4>
        <el-alert
          v-for="(tip, index) in currentRecipe?.tips"
          :key="index"
          :title="tip"
          type="info"
          :closable="false"
          class="recipe-tip"
        />
      </div>
    </el-dialog>

    <!-- 添加到膳食计划对话框 -->
    <el-dialog
      v-model="mealPlanDialogVisible"
      title="添加到膳食计划"
      width="30%"
    >
      <el-form :model="mealPlanForm" label-width="80px">
        <el-form-item label="日期">
          <el-date-picker
            v-model="mealPlanForm.date"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="餐次">
          <el-select v-model="mealPlanForm.mealType" placeholder="选择餐次" style="width: 100%">
            <el-option label="早餐" value="breakfast" />
            <el-option label="午餐" value="lunch" />
            <el-option label="晚餐" value="dinner" />
            <el-option label="加餐" value="snack" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="mealPlanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddToMealPlan">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Star, StarFilled, Plus, Search } from '@element-plus/icons-vue'
import { favoriteRecipe, unfavoriteRecipe } from '@/api/recipes'
import { useStore } from 'vuex'
import { formatDate } from '@/utils/date'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()
const loading = ref(false)

// 食谱列表数据
const recipes = computed(() => store.state.recipe.recipes)
const total = computed(() => store.state.recipe.total)

// 筛选表单
const filterForm = reactive({
  keyword: '',
  category: '',
  difficulty: '',
  time: '',
  sortBy: 'popularity'
})

// 分页
const currentPage = ref(1)
const pageSize = ref(12)

// 对话框
const dialogVisible = ref(false)
const mealPlanDialogVisible = ref(false)
const currentRecipe = ref(null)

// 添加到膳食计划表单
const mealPlanForm = reactive({
  date: new Date(),
  mealType: ''
})

// 食谱分类
const categories = [
  { label: '中式菜品', value: 'chinese' },
  { label: '西式料理', value: 'western' },
  { label: '日韩料理', value: 'japanese_korean' },
  { label: '快手菜', value: 'quick' },
  { label: '素食', value: 'vegetarian' },
  { label: '烘焙', value: 'baking' }
]

// 搜索处理
const handleSearch = async () => {
  try {
    loading.value = true
    await store.dispatch('recipe/getRecipes', {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...filterForm
    })
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    keyword: '',
    category: '',
    difficulty: '',
    time: '',
    sortBy: 'popularity'
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 显示食谱详情
const showRecipeDetail = (recipe) => {
  currentRecipe.value = recipe
  dialogVisible.value = true
}

// 收藏/取消收藏
const toggleFavorite = async (recipe) => {
  if (!recipe) return
  try {
    loading.value = true
    if (recipe.isFavorite) {
      await unfavoriteRecipe(recipe.id)
      ElMessage.success('已取消收藏')
    } else {
      await favoriteRecipe(recipe.id)
      ElMessage.success('已添加到收藏')
    }
    // 更新 store 中的收藏状态
    await store.dispatch('recipe/updateFavoriteStatus', {
      recipeId: recipe.id,
      isFavorite: !recipe.isFavorite
    })
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 添加到膳食计划
const addToMealPlan = (recipe) => {
  currentRecipe.value = recipe
  mealPlanDialogVisible.value = true
}

// 确认添加到膳食计划
const confirmAddToMealPlan = async () => {
  if (!currentRecipe.value) return
  try {
    await store.dispatch('meals/addMealRecord', {
      date: formatDate(mealPlanForm.date),
      mealType: mealPlanForm.mealType,
      foodId: currentRecipe.value.id,
      amount: 1, // 默认一份
      note: `来自食谱：${currentRecipe.value.name}`
    })
    ElMessage.success('已添加到膳食计划')
    mealPlanDialogVisible.value = false
    mealPlanForm.mealType = '' // 重置表单
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error('添加失败')
  }
}

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  const types = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

// 日期限制
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 不能选择过去的日期
}

// 初始化数据
onMounted(async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    loading.value = true
    await store.dispatch('recipe/getRecipes', {
      page: 1,
      pageSize: 12,
      ...filterForm
    })
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.recipes-container {
  padding: 20px;

  .filter-card {
    margin-bottom: 20px;

    .filter-form {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
    }
  }

  .recipe-list {
    margin-bottom: 20px;
  }

  .recipe-card {
    margin-bottom: 20px;
    transition: transform 0.3s;

    &:hover {
      transform: translateY(-5px);
    }

    .recipe-image {
      position: relative;
      height: 200px;

      .el-image {
        width: 100%;
        height: 100%;
      }

      .image-placeholder {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: var(--el-fill-color-light);
        
        .el-icon {
          font-size: 48px;
          color: var(--el-text-color-secondary);
        }
      }

      .recipe-tags {
        position: absolute;
        top: 10px;
        right: 10px;
        display: flex;
        gap: 8px;
      }
    }

    .recipe-content {
      padding: 16px;

      .recipe-title {
        margin: 0 0 8px;
        font-size: 18px;
        cursor: pointer;
        
        &:hover {
          color: var(--el-color-primary);
        }
      }

      .recipe-desc {
        margin: 0 0 16px;
        font-size: 14px;
        color: var(--el-text-color-secondary);
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .recipe-info {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .nutrition-info {
          font-size: 14px;
          color: var(--el-text-color-secondary);
        }

        .action-buttons {
          display: flex;
          gap: 8px;
        }
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}

.recipe-dialog {
  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
    }

    .dialog-actions {
      display: flex;
      gap: 12px;
    }
  }

  .recipe-detail {
    margin-top: 20px;

    h4 {
      margin: 20px 0 12px;
      font-size: 16px;
      color: var(--el-text-color-primary);
    }

    .recipe-tip {
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style> 